package com.yishusmt.wechatapi.wechatdev.serviceImpl;

import com.yishusmt.wechatapi.wechatdev.constant.RedisConstant;
import com.yishusmt.wechatapi.wechatdev.constant.SemanticMatchingConstant;
import com.yishusmt.wechatapi.wechatdev.entity.ReceivingAddressEntity;
import com.yishusmt.wechatapi.wechatdev.entity.WechatMemebrEntity;
import com.yishusmt.wechatapi.wechatdev.mapper.ReceivingAddressInfoMapper;
import com.yishusmt.wechatapi.wechatdev.mapper.SearchInfoEntityMapper;
import com.yishusmt.wechatapi.wechatdev.mapper.SearchInfoMapper;
import com.yishusmt.wechatapi.wechatdev.mapper.WechatMemebrInfoMapper;
import com.yishusmt.wechatapi.wechatdev.service.MessageHandleService;
import com.yishusmt.wechatapi.wechatdev.service.MessageService;
import com.yishusmt.wechatapi.wechatdev.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;

/**
 * 业务消息处理
 *
 * @author zhangyi
 * @date 2018/8/31 11:46
 */
@Service
@Slf4j
public class MessageHandleServiceImpl implements MessageHandleService {

    @Autowired
    private CustomerUtil customerUtil;

    @Autowired
    private KeywordUtil keywordUtil;

    @Autowired
    private SearchInfoMapper searchInfoMapper;

    @Autowired
    private LocalMessageUtil localMessageUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WechatMemebrInfoMapper wechatMemebrInfoMapper;

    @Autowired
    private ReceivingAddressInfoMapper receivingAddressInfoMapper;


    /**
     * 处理本地业务需求,处理不了的时候返回null
     *
     * @param mes
     * @return
     */
    @Override
    public String userLocalMessageHandle(String mes, String openId) {
        //待返回的字符串
        String result = null;
        //关键字id列表
        List<Long> keyword = keywordUtil.keyword(mes);
        //一个关键字id所对应的对各相似关键字的id模型
        Map<Integer, List<Long>> listMap = new HashMap<>();
        //待存储的关键字的id列表
        List<Long> v = new ArrayList<>();
        keyword.stream().forEach(e -> {
            Integer integer = searchInfoMapper.selectSerachDesc(e);
            v.add(e);
            listMap.put(integer, v);
        });
        Set<Map.Entry<Integer, List<Long>>> entries = listMap.entrySet();
        Iterator<Map.Entry<Integer, List<Long>>> iterator = entries.iterator();
        Integer style = 0;
        while (iterator.hasNext()) {
            Map.Entry<Integer, List<Long>> next = iterator.next();
            style = next.getKey();
        }

        //临时保存
        Integer[] checkCode = new Integer[]{style};
        boolean[] flag = new boolean[]{false};
        //权限提示字符串
        String[] checkStr = new String[1];
//        System.out.println(checkStr+"--"+mes+openId+checkCode[0]+"--"+style);
        //权限拦截
        Arrays.asList(SemanticMatchingConstant.BLOCK).stream()
                .forEach(e -> {
                 if(checkCode[0].equals(e)){
                    //需要验证
                     //输入手机号或者邮箱
                     checkStr[0] = localMessageUtil.IDVerification(mes, openId);
                     flag[0] = true;
                 }
                });
        //输入手机或者邮箱格式判断
        if(StringUtils.contains(checkStr[0],"::")){
            return checkStr[0].replace("::","");
        }else if(StringUtils.contains(checkStr[0],"---")){
            return checkStr[0].replace("---","");
        }
        //去redis里去验证token是否正确
        String salt = MD5Util.encryptString(openId);
        String check = redisUtil.get(RedisConstant.USER_TOKEN + salt);
        boolean checkPan = Optional.ofNullable(check).isPresent();

        boolean checkTemp = false;
        //使用MD5加密作为key,now compare two encryption number this is check other is AES encrytion
        if(checkPan){
            if(check.equals(AESUtil.encryptString(openId,salt))){
                checkTemp = true;
            }
        }
        log.info("flag[0]={}--------checkTemp={}",flag[0],checkTemp);
        if(flag[0] && checkTemp){
            WechatMemebrEntity wechatMemebrEntity =
                    wechatMemebrInfoMapper.selectMemberByOpenId(openId);
            boolean isMember = Optional.ofNullable(wechatMemebrEntity).isPresent();
            if(!isMember){
                return "您需要验证账户"+
                        "\n请输入：手机号1XX7868XXXX" +
                        "\n或者：邮箱XXXXXX@XX.com";
            }
            //PC账户和移动账户一起查
            Long memberId = wechatMemebrEntity.getMemberId()==null?
                    wechatMemebrEntity.getId():wechatMemebrEntity.getMemberId();
            //验证账号
            switch (style) {
                case SemanticMatchingConstant.A:
                    //查询收获地址（1）
                    result = localMessageUtil.harvestAddress(memberId);
                    break;
                case SemanticMatchingConstant.B:
                    //查询我的资料（2）
                    result = localMessageUtil.harvestMineData(memberId);
                    break;
                case SemanticMatchingConstant.C:
                    //查询我的订单（3）
                    result = localMessageUtil.harvestOrder(memberId);
                    break;
                case SemanticMatchingConstant.D:
                    //查询我的快递（4）
                    result = localMessageUtil.harvestTrackingNumber(mes);
                    break;
                case SemanticMatchingConstant.E:
                    //查询发布需求（5）
                    result = localMessageUtil.harvestDemand(memberId);
                    break;
                case SemanticMatchingConstant.F:
                    //所有加工厂（6）
                    result = "所有加工厂";
                    break;
                case SemanticMatchingConstant.G:
                    //加工厂+名字（7）
                    result = "查询指定的加工厂";
                    break;
                case SemanticMatchingConstant.H:
                    //平台规范（8）
                    break;
                case SemanticMatchingConstant.I:
                    //服务规范（9）
                    break;
                case SemanticMatchingConstant.J:
                    //项目管控（10）
                    break;
                case SemanticMatchingConstant.K:
                    //品控规则（11）

                    break;
                case SemanticMatchingConstant.L:
                    //合作加盟（12）
                    break;
                default:
                    result = "";
                    break;
            }
        }else{
            log.info("check={}, checkStr[0]={} result={}",check,checkStr,result);
            if(check == null){
                //此时应该是用户验证，返回验证提示信息
                log.info("没有用户的TOKEN!!!");
                if("".equals(checkStr[0])){
                    return "您需要先验证账户，" +
                            "\n请输入：手机号1XX7868XXXX" +
                            "\n或者：邮箱XXXXXX@XX.com";
                }
                return checkStr[0];
            }else if(check != null){
                log.info("缓存中有用户的TOKEN!!!");
                return result;
            }
        }
/*
        好了这里有个问题：
           一个是智能客服返回的是第三方处理的数据，
           一个是需要返回的本地查询的数据，
           两个都是返回的result结果，
           怎么校验输入的信息是需要客服回复的还是需要本地回复的
 */
        log.info("拦截标志flag[0]{}  返回结果集：{}",flag[0],result);
        if("".equals(result)){
            //没有查到
            return null;
        }else if(result == null){
            if(flag[0]){
                return null;
            }else{
                //本地的
                return "您需要先验证账户，" +
                        "\n请输入：手机号1XX7868XXXX" +
                        "\n或者：邮箱XXXXXX@XX.com";
            }
        }else{
            //正常查询
            return result;
        }
    }

    /**
     * 处理其他业务需求(针对图灵智能机器人)
     *
     * @param mes
     * @return
     */
    @Override
    public String userMessageHandle(String mes) throws IOException, URISyntaxException {
        return customerUtil.robot(mes);
    }
}
